package com.owulia.leetcode.num;

public class CatchRain {


    public static int trap(int[] height) {
        if (height.length <= 2) {
            return 0;
        }
        int[] h1 = new int[height.length];
        h1[0] = height[0];
        for (int i = 1; i < height.length; i++) {
            h1[i] = Math.max(h1[i - 1], height[i]);
        }
        int[] h2 = new int[height.length];
        h2[height.length - 1] = height[height.length - 1];
        for (int i = height.length - 2; i >= 0; i--) {
            h2[i] = Math.max(h2[i + 1], height[i]);
        }
        int result = 0;
        for (int i = 0; i < height.length; i++) {
            result += Math.min(h1[i], h2[i]) - height[i];
        }
        return result;
    }

    public static void main(String[] args) {
        int[] a = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        int[] b = {4, 2, 0, 3, 2, 5};
        System.out.println(trap(b));
    }


    public static int trap2(int[] height) {
        if (height.length <= 2) {
            return 0;
        }
        int left = 0, right = height.length - 1;
        int leftMax = height[0], rightMax = height[height.length - 1];
        int ans = 0;
        while (left < right) {
            leftMax = Math.max(leftMax, height[left]);
            rightMax = Math.max(rightMax, height[right]);
            if (leftMax < rightMax) {
                ans += leftMax - height[left];
                left++;
            } else {
                ans += rightMax - height[right];
                right--;
            }
        }
        return ans;
    }

}
